//
// Created by 周杰 on 2020/1/13.
//

#include "HisAndOTSUTest.h"

const string image_path = "/Volumes/D/study/machinelearning/opencv/testpic/lenacolor.bmp";

/**
 * 分割出来的结果还是比较好
 */
void HisAndOTSUTest::test() {
    Mat source_image = imread(image_path);
    imshow("source image.", source_image);

    //转换成灰度图片
    Mat gray_image;
    cvtColor(source_image, gray_image, COLOR_BGR2GRAY);
    imshow("gray image.", gray_image);

    int channels[] = {0}; //查看第0个通道的数据
    MatND hist;     //获取的直方图结果
    int histSize[] = {256}; //我理解是横坐标，分块成255份
    float range[] = {0, 256};  //查看每个通道里边的灰度范围
    const float *ranges[] = {range};//第一个就对应channels里边的一个数
    int dims = 1;//只取一个维度，所以是1
    int nimages = 1;//图片数量
    //获取直方图数据
    calcHist(&gray_image, nimages, channels, Mat(), hist, dims, histSize, ranges, true, false);

    double maxVal = 0;
    minMaxLoc(hist, 0, &maxVal, 0, 0);
    printf("max value: %f \n", maxVal);

    //创建直方图空白图
    Mat hisR(histSize[0], histSize[0], CV_8UC3);
    printf("rows: %f cols: %f \n", hisR.rows, hisR.cols);

    for (int i = 0; i < histSize[0]; ++i) {
        float bVal = hist.at<float>(i);
        printf("bVal: %f  rows: %f \n", bVal, hisR.rows);
        //将线画到空白图上
        line(hisR, Point(i, hisR.rows), Point(i, hisR.rows - bVal * histSize[0] / maxVal), Scalar(0, 0, 255));
    }
    imshow("his image.", hisR);

    //使用大津算法对图片进行分割
    Mat otsu_image;
    //这里这个阀值设置是无效的内部代码中已经实现了
    threshold(gray_image, otsu_image, 0, 0xff, ThresholdTypes::THRESH_OTSU);
    imshow("otsu image.", otsu_image);

    waitKey();
    destroyAllWindows();
}